// pages/me/order/index.js
import util from '../../../utils/utils';
import User from "../../../utils/user";
import {
  CartHttp
} from '../../../api/cart.js'
import Dialog from "../../../dist/dialog/dialog";
import {
  UserHttp
} from "../../../api/user";
const cartModel = new CartHttp();
const userHttp = new UserHttp();

Page({
  payComponentEl: null,
  /**
   * 页面的初始数据
   */
  data: {
    value: '',
    initUser: true,
    statusMap: [
      //0全部订单,1待付款,2待收货,3已收货,4退货/退款
      {
        id: 1,
        name: '全部订单'
      },
      {
        id: 2,
        name: '待支付'
      },
      {
        id: 3,
        name: '待收货'
      },
      {
        id: 4,
        name: '已收货'
      },
      {
        id: 5,
        name: '退货退款'
      },

    ],
    orderId: 0,
    listData: [],
    listPage: 1,
    listEmpty: false,
    listMore: true,
    ServiceText: false,
    isShowPayBox: false,
    payOrderId: false,
    ShowRedPacket: false,
    d_orderId: '',
    type: 1,
    status: 1,
  },
  initPage: function (option) {
    let self = this;
    wx.hideShareMenu();
    let type = 2;
    if (option.hasOwnProperty('type')) {
      type = util.fixInt(option['type']);
    }
    self.setData({
      type: type
    });
    this.payComponentEl = this.selectComponent('#payBox');
    self.initData(true);
    /**
     * 弹开红包框
     */
    // if(option.hasOwnProperty('d_orderId') && this.data.d_orderId !== option['d_orderId']){
    //   setTimeout(function () {
    //     self.setData({
    //       d_orderId:option['d_orderId'],
    //       ShowRedPacket:true,
    //     });
    //   },300);
    // }
  },
  openRedPacket: function () {
    let self = this;
    /**
     * 拆红包功能
     */
    util.request({
      url: '/order/generateRedPacket',
      isJava: true,
      handle: true,
      loading: true,
      data: {
        unionOrderId: this.data.d_orderId,
        orderType: 4
      },
      callback: function (result) {
        self.setData({
          ShowRedPacket: false,
        });
        if (result.status === 'ok') {
          util.toPage({
            currentTarget: {
              dataset: {
                page: result.res.url + '&is_mini=1',
                title: '开红包'
              }
            }
          });
        } else {
          util.msg(result.msg);
        }
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.initUser !== true) {
      return false;
    }
    this.initData(true);
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let self = this;
    if (self.data.listMore === true) {
      let param = self.getApiParam(false);
      util.request({
        url: param.url,
        data: param,
        isJava: true,
        loading: true,
        callback: function (result) {
          let listData = self.data.listData;
          let _data = [];
          let _total = 0;
          let more = false;
          //处理统一的数据结构
          if (result['res']['list']) {
            _data = self.formatData(result['res']['list']);
            _total = result['res']['total'];
          }
          for (let i = 0; i < _data.length; i++) {
            listData.push(_data[i]);
          }
          if (listData.length < _total) {
            more = true;
          }
          listData = self.formatlistData(listData)
          self.setData({
            listData: listData,
            listPage: param.pageNum,
            listMore: more
          });
          wx.hideNavigationBarLoading();
          wx.stopPullDownRefresh();
        }
      });
    }
  },
  onChange(e) {
    this.setData({
      value: e.detail
    });
  },
  onSearch: function (event) {
    if (this.data.value === '') {
      util.msg('请输入要搜索的订单号!');
      return false;
    }
    if (this.data.value.length < 6) {
      util.msg('最少需要输入订单号中的6位!');
      return false;
    }
    this.getApiData(true);
  },
  formatData: function (list) {
    for (let i = 0; i < list.length; i++) {
      // realOrderPrice
      list[i]['order_amount'] = util.formatMoney(list[i]['realPayPrice']);
      list[i]['order_need_pay'] = util.formatMoney(list[i]['realOrderPrice']);
      list[i]['create_time'] = util.formatTime('yyyy-MM-dd HH:mm:ss', list[i]['createTm']);
      list[i]['address'] = list[i]['address'].replace(' ', '');
      if (list[i]['orderStatus'] === 0) {
        list[i]['orderStatusDesc'] = '待付款';
      }
    }
    return list;
  },
  switchStatus: function (event) {
    let old_type = this.data.status;
    let type = parseInt(event.detail.itemid);
    if (old_type !== type) {
      this.setData({
        status: type,
      });
      this.initData(true);
    }
  },
  onShow() {
    this.initData(true)
  },
  /**
   * 处理查询参数
   * @param ref
   * @returns {{pageSize: number, type: int, orderStatus: number, url: string}}
   */
  getApiParam: function (ref) {
    let update = ref || false;
    let _data = {
      url: '/order/xhbOrderList',
      orderStatus: this.data.status - 1,
      orderMainType: 1,
      type: 0,
      pageSize: 10,
    };
    if (!update) {
      _data['pageNum'] = this.data.listPage + 1;
    } else {
      _data['pageNum'] = 1;
    }
    if (this.data.value !== '' && this.data.value.length >= 6) {
      _data['orderNumber'] = this.data.value;
    }
    return _data;
  },
  getApiData: function (ref) {
    let update = ref || false;
    let self = this;
    let param = this.getApiParam(update);
    wx.showNavigationBarLoading();
    util.request({
      url: param.url,
      isJava: 1,
      data: param,
      loading: 1,
      callback: function (result) {
        let _data = [];
        let _total = 0;
        //处理统一的数据结构
        if (result['res']['list']) {
          _data = self.formatData(result['res']['list']);
          _total = result['res']['total'];
        }
        let more = false;
        if (_data.length < _total) {
          more = true;
        }
        _data = self.formatlistData(_data)
        self.setData({
          isShowPaymentPopup: false,
          listData: _data,
          listEmpty: _data <= 0,
          listPage: param.pageNum,
          listMore: more
        });
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  formatlistData(res) {
    for (let i = 0; i < res.length; i++) {
      let goodList = res[i]["goodsList"]
      for (let y = 0; y < goodList.length; y++) {
        if (goodList[y]["name"] != res[i]["goodsName"]) {
          res[i]["goodsName"] = ""
        }
      }
    }
    return res
  },
  initData: function (ref) {
    let self = this;
    let update = ref || false;
    self.getApiData(update);
  },
  payOrder: function (e) {
    let orderId = e.currentTarget.dataset.orderid;
    this.openPayBox(orderId);
  },
  openPayBox: function (order_id) {
    this.setData({
      orderId: order_id,
      isShowPayBox: true,
    });
    this.payComponentEl.switchPayment(this.data.paymentMethod);
    this.payComponentEl.setShowPayTime(false);
    this.payComponentEl.setOrderID(order_id);
    this.payComponentEl.openPayMethod();
  },
  payComplete: function (res) {
    console.log(res)
    let self = this;
    self.setData({
      isShowPayBox: false,
    });
    // if (res.detail.status === 'complete') {
    //   let url = '';
    //   url = '/pages/goods/paySuccess/paySuccess?id=' + self.data.orderId
    //   setTimeout(function () {
    //     util.toPage(url, false, true);
    //   }, 300);
    // }
    self.initData(true);
  },
  onCancelOrder(e) {
    let orderId = e.currentTarget.dataset.orderid;
    let that = this;
    wx.showModal({
      title: '是否取消订单',
      // content: '是否取消订单',
      success: function (res) {
        if (res.confirm) {
          //如果订单状态是待付款则是直接取消
          userHttp.getOrderOff({
            unionOrderId: orderId
          }).then((res) => {
            that.initData(true);
            // wx.navigateBack({
            // delta: 1
            // });
          })
        }
      }
    });
  },
  reCart: function (e) {
    let orderId = e.currentTarget.dataset.orderid;
    util.request({
      url: '/order/getOrderDetail',
      data: {
        orderNumber: orderId
      },
      isJava: 1,
      loading: true,
      callback: function (result) {
        let goods = [];
        let orderGoods = result.res.goodsInfo;
        let param = {
          storeId: result.res.storeId,
          dispatchType: 1,
          luckyBean: 0,
          payType: 4,
          goods: [],
          userId: User.UserData['uid']
        };
        for (let i = 0; i < orderGoods.length; i++) {
          goods.push({
            sku_id: orderGoods[i]['goodsSkuId'],
            spu_id: orderGoods[i]['goodsSpuId'],
            amount: orderGoods[i]['goodsNum'],
          });
          param['goods'].push({
            skuId: orderGoods[i]['goodsSkuId'],
            spuId: orderGoods[i]['goodsSpuId'],
            skuAmount: orderGoods[i]['goodsNum']
          });
        }
        cartModel.goodsDiscount(param).then(function (res) {
          util.toPage('/pages/goods/pendingOrder/pendingOrder?id=' + JSON.stringify(goods) + '&storeId=' + result.res.storeId + '&serviceId=' + result.res.storeServiceId);
        }).catch(function () {

        });
      }
    });

  }
});